#include "testhelper.hpp"

int test_select(TestHelper *th, int timeout)
{
    SelectHelper *sh = new SelectHelper();
    int ret;

    for (const auto &f: th->get_files()) {
        f->set_nonblock(true);
        sh->add_file(f, true, false);
    }

    std::cout << "timeout: " << timeout << std::endl;
    do {
        ret = sh->select(timeout);
        if (ret < 0) {
            std::cerr << "select error: " << errno << std::endl;
            return ret;
        } else if (ret == 0) {
            std::cerr << "select timeout" << std::endl;
            return -ETIMEDOUT;
        }

        for (auto fd: sh->get_fds()) {
            if (FD_ISSET(fd, &sh->get_readfds())) {
                FileDesc *f = sh->get_file_from_fd(fd);
                if (!f) {
                    std::cerr << "unkown fd: " << fd << std::endl;
                    continue;
                }

                std::cout << "read from: " << f->get_name() << std::endl;
                std::string readbuf = f->read();
                std::cout << readbuf << std::endl;
                if (readbuf == "quit") {
                    return 0;
                }
            }
        }
    } while (1);

    delete sh;

    return 0;
}

int main(int argc, const char *argv[])
{
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " timeout(ms)" << std::endl;
        return -1;
    }

    TestHelper *th = new TestHelper(5);
    int timeout = std::stoi(argv[1]);
    int ret;

    th->create_files();

    ret = test_select(th, timeout);

    th->remove_files();

    delete th;

    return ret;
}
